package com.ones.mqtt.server.util;

import com.ones.mqtt.server.model.OnesMqttPublishDto;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.spring.server.MqttServerTemplate;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.tio.utils.hutool.StrUtil;

import java.nio.charset.StandardCharsets;

/**
 * MqttServer工具类
 * @author Clark
 * @version 2024-06-11
 */
@Slf4j
public class OsMqttServerUtils implements SmartInitializingSingleton {
    @Autowired
    private ApplicationContext applicationContext;
    private MqttServerTemplate server;

    /**
     * 单例 bean 初始化完成之后从 ApplicationContext 中获取 bean
     */
    @Override
    public void afterSingletonsInstantiated() {
        this.server = applicationContext.getBean(MqttServerTemplate.class);
    }

    /**
     * 发布消息
     * @param dto
     * @return
     */
    public boolean publish(OnesMqttPublishDto dto) {
        boolean result;
        if (StrUtil.isBlank(dto.getClientId())) {
            result = this.server.publishAll(dto.getTopic(), dto.getPayload().getBytes(StandardCharsets.UTF_8), dto.getQoS(), dto.isRetain());
        } else {
            result = this.server.publish(dto.getClientId(), dto.getTopic(), dto.getPayload().getBytes(StandardCharsets.UTF_8), dto.getQoS(), dto.isRetain());
        }
        log.debug("publish:{}, result:{}", dto, result);
        return result;
    }
}